package com.vavr.checkincms.service.impl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.text.CharSequenceUtil;
import com.vavr.checkincms.common.constant.CommonConstants;
import com.vavr.checkincms.common.domain.ResultEnum;
import com.vavr.checkincms.domain.bo.SystemUserInfoBO;
import com.vavr.checkincms.domain.data.SystemUserInfoDO;
import com.vavr.checkincms.domain.dto.SystemUserInfoDTO;
import com.vavr.checkincms.mapper.SystemLoginMapper;
import com.vavr.checkincms.service.SystemLoginService;
import com.vavr.checkincms.util.CheckinRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

/**
 * CheckinServiceImpl
 *
 * @since 2024.08
 */
@Slf4j
@Service
public class SystemLoginServiceImpl implements SystemLoginService {
    /**
     * 签到时间相关配置
     */
    private final SystemLoginMapper systemLoginMapper;


    public SystemLoginServiceImpl(SystemLoginMapper systemLoginMapper) {
        this.systemLoginMapper = systemLoginMapper;
    }


    @Override
    public String login(HttpServletRequest request, HttpServletResponse response, SystemUserInfoBO bo) {
        if(bo == null || Strings.isEmpty(bo.getOperatorAccount()) || Strings.isEmpty(bo.getOperatorCode())) {
           return ResultEnum.LOGIN_ERROR.getMsg();
        }
        // 查询用户信息,组装session信息
        SystemUserInfoDO userInfoDO = systemLoginMapper.queryUserInfo(bo.getOperatorAccount(),bo.getOperatorCode());
        if(userInfoDO != null) {
            // 生成登录cooKie 信息
            Cookie cookie = new Cookie(CommonConstants.CHECKIN_CMS_COOKIE_ID, userInfoDO.getOperatorId());
            cookie.setPath(CommonConstants.CHECKIN_COOKIE_PATH);
            cookie.setMaxAge(60 * 60 * 24);
            cookie.setHttpOnly(true);
            String header = request.getHeader(CommonConstants.X_FORWARDED_PROTO);
            if (CharSequenceUtil.isNotBlank(header) && header.equalsIgnoreCase("https")) {
                cookie.setSecure(true);
            }
            response.addCookie(cookie);
            CheckinRequestUtils.setUserToRequestAttributes(new SystemUserInfoDTO().setOperatorId(userInfoDO.getOperatorId()));
            return ResultEnum.OK.getMsg();
        }
        return ResultEnum.LOGIN_ERROR.getMsg();
    }
}
